﻿using Microsoft.EntityFrameworkCore;

namespace RBAC.Data;
public class RbacDbContext : DbContext
{
    public RbacDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasMany(m => m.Roles).WithMany(m => m.Users)
            .UsingEntity<Dictionary<string, object>>("UserInRole",
            right => right.HasOne<Role>(nameof(Role)).WithMany().HasForeignKey("RoleId").HasPrincipalKey(nameof(Role.Id)).OnDelete(DeleteBehavior.Cascade),
            left => left.HasOne<User>(nameof(User)).WithMany().HasForeignKey("UserId").HasPrincipalKey(nameof(User.Id)).OnDelete(DeleteBehavior.Cascade),
            builder =>
            {
                builder.HasKey("UserId", "RoleId");
                builder.HasIndex("RoleId");
                builder.HasIndex("UserId");
                builder.ToTable("UserInRoles");
            });

        //https://learn.microsoft.com/zh-cn/ef/core/modeling/relationships/many-to-many
    }
}
